package com.bc.trade.channel.buzi;

import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.bc.common.CommonEnum.OrderStatus;
import com.bc.common.CommonEnum.Resp;
import com.bc.common.message.DFReq;
import com.bc.common.message.DFResp;
import com.bc.common.message.TransferQrcodeReq;
import com.bc.common.message.TransferQrcodeResp;
import com.bc.trade.channel.IChannel;
import com.bc.trade.config.SystemConfig;
import com.bc.trade.message.QueryCardInfoReq;
import com.bc.trade.message.QueryCardInfoResp;
import com.bc.trade.message.QueryOrderResp;
import com.bc.trade.message.QuickPayReq;
import com.bc.trade.message.QuickPayResp;
import com.bc.trade.message.QuickPaySetReq;
import com.bc.trade.message.QuickPaySetResp;
import com.bc.trade.message.RefundReq;
import com.bc.trade.message.RefundResp;
import com.bc.trade.message.SendSMSReq;
import com.bc.trade.message.SendSMSResp;
import com.bc.trade.message.UnionPayReq;
import com.bc.trade.message.UnionPayResp;
import com.bc.trade.model.TradeOrder;
import com.fs.common.util.FSDate;
import com.fs.common.util.FSHttp;
import com.fs.common.util.FSLog;
import com.fs.common.util.FSMD5;
import com.fs.common.util.FSMoney;
import com.fs.common.util.FSString;
import com.jfinal.kit.StrKit;

public class BuziChannel implements IChannel {
	private final String MERCHANT_NO = SystemConfig.channelConfig.get("buzi_merchant_no");
	private final String KEY = SystemConfig.channelConfig.get("buzi_key");
	private final String TRADE_URL = SystemConfig.channelConfig.get("buzi_trade_url");
	private final String TRADE_QUERY_URL = SystemConfig.channelConfig.get("buzi_trade_query_url");
	private final String TRADE_NOTIFY_URL = SystemConfig.channelConfig.get("buzi_trade_notify_url");
	private final String DF_URL = SystemConfig.channelConfig.get("buzi_df_url");
	private final String DF_QUERY_URL = SystemConfig.channelConfig.get("buzi_df_query_url");

	public TransferQrcodeResp transferQrcode(TransferQrcodeReq req, TradeOrder order) throws Exception {
		TransferQrcodeResp resp = new TransferQrcodeResp(req);
		resp.setIsHtml("1");
		TreeMap<String, String> map = new TreeMap<>();
		map.put("pay_memberid", MERCHANT_NO);
		map.put("pay_orderid", order.getOrderNo());
		map.put("pay_applydate", FSDate.getDateTime());
		map.put("pay_bankcode", "916");
		map.put("pay_notifyurl", TRADE_NOTIFY_URL);
		map.put("pay_callbackurl", req.getCallbackUrl());
		map.put("pay_amount", FSMoney.changeF2Y(order.getAmount().longValue()));
		map.put("pay_md5sign", FSMD5.sortSign(map, "key=" + KEY));
		map.put("pay_productname", "商品收银");
		map.put("pay_attach", order.getOrderNo());
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("请求布子数据：" + content);
		try {
			String result = FSHttp.postFormString(TRADE_URL, content, "UTF-8");
			if (StrKit.isBlank(result)) {
				resp.setCodeAndMsg(Resp.Fail.getCode(), "请求渠道转账二维码页面失败");
				resp.setHtml("");
				return resp;
			}
			String result1 = result
					.replace("/Public/Pay/css/toastr.min.css", "http://www.coolsk.cn/Public/Pay/css/toastr.min.css")
					.replace("/Public/Pay/js/jquery.min.js", "http://www.coolsk.cn/Public/Pay/js/jquery.min.js")
					.replace("/Public/Pay/images/timg.gif", "http://www.coolsk.cn/Public/Pay/images/timg.gif")
					.replace("/Public/Pay/js/jquery.qrcode.min.js", "http://www.coolsk.cn/Public/Pay/js/jquery.qrcode.min.js")
					.replace("/Public/Pay/js/toastr.min.js", "http://www.coolsk.cn/Public/Pay/js/toastr.min.js")
					.replace("/Public/Pay/js/dourl.js", "http://www.coolsk.cn/Public/Pay/js/dourl.js")
					.replace("/Pay/images/qrcode_timeout.png", "http://www.coolsk.cn/Pay/images/qrcode_timeout.png");
			FSLog.api.info("布子响应数据：" + result1);
			resp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
			resp.setHtml(result1);
		} catch (Exception e) {
			FSLog.api.error("布子交易请求异常" + e);
			resp.setHtml("");
			resp.setCodeAndMsg(Resp.Fail.getCode(), "请求渠道转账二维码页面失败");
		}
		return resp;
	}

	@Override
	public QueryOrderResp query(TradeOrder order) throws Exception {
		QueryOrderResp resp = new QueryOrderResp();
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("merchantNo", MERCHANT_NO);
		map.put("pay_orderid", order.getOrderNo());
		map.put("pay_md5sign", FSMD5.sortSign(map, "key=" + KEY));
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("请求布子订单查询数据：" + content);
		try {
			String result = FSHttp.postFormString(TRADE_QUERY_URL, content, "UTF-8");
			FSLog.api.info("布子订单查询响应数据：" + result);
			if (StrKit.notBlank(result)) {
				resp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
				JSONObject obj = JSONObject.parseObject(result);
				String returncode = obj.getString("returncode");
				if ("00".equals(returncode)) {
					String payStatus = obj.getString("trade_state");
					if ("SUCCESS".equals(payStatus)) {
						order.setOrderStatus(OrderStatus.Success.getValue());
						resp.setOriginalRespCode(Resp.Success.getCode());
						resp.setOriginalRespMsg(Resp.Success.getMsg());
					} else if ("NOTPAY".equals(payStatus)) {
						order.setOrderStatus(OrderStatus.InProcess.getValue());
						resp.setOriginalRespCode(Resp.InProcess.getCode());
						resp.setOriginalRespMsg(Resp.InProcess.getMsg());
					} else {
						order.setOrderStatus(OrderStatus.Fail.getValue());
						resp.setOriginalRespCode(Resp.Fail.getCode());
						resp.setOriginalRespMsg(Resp.Fail.getMsg());
					}
					order.update();
				}
			}
		} catch (Exception e) {
			FSLog.api.error("布子交易查询异常:" + e);
			resp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
		}
		return resp;
	}

	@Override
	public DFResp df(DFReq req, TradeOrder order) throws Exception {
		DFResp rsp = new DFResp(req);
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("mchid", MERCHANT_NO);
		map.put("out_trade_no", order.getOrderNo());
		map.put("money", FSMoney.changeF2Y(order.getAmount().longValue()));
		map.put("cardnumber", req.getAccountCardNo());
		map.put("accountname", req.getAccountName());
		map.put("acqCode", "8099");
		map.put("bankname", req.getBankName());
		map.put("province", req.getProvince());
		map.put("city", req.getCity());
		map.put("subbranch", req.getBranchName());
		map.put("pay_md5sign", FSMD5.sortSign(map, "key=" + KEY));
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("请求布子代付数据：" + content);
		try {
			String result = FSHttp.postFormString(DF_URL, content, "UTF-8");
			FSLog.api.info("布子代付响应数据：" + result);
			JSONObject returnObj = JSONObject.parseObject(result);
			String status = returnObj.getString("status");
			if ("success".equals(status)) {
				order.setChannelOrderNo(returnObj.getString("transaction_id"));
				order.update();
				rsp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
			} else {
				rsp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
			}
		} catch (Exception e) {
			FSLog.api.error(e);
			rsp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
		}
		return rsp;
	}

	@Override
	public QueryOrderResp dfQuery(TradeOrder order) throws Exception {
		QueryOrderResp resp = new QueryOrderResp();
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("mchid", MERCHANT_NO);
		map.put("out_trade_no", order.getOrderNo());
		map.put("pay_md5sign", FSMD5.sortSign(map, "key=" + KEY));
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("请求布子代付订单查询数据：" + content);
		try {
			String result = FSHttp.postFormString(DF_QUERY_URL, content, "UTF-8");
			FSLog.api.info("布子代付订单查询响应数据：" + result);
			if (StrKit.notBlank(result)) {
				resp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
				JSONObject obj = JSONObject.parseObject(result);
				String status = obj.getString("status");
				if ("success".equals(status)) {
					String refCode = obj.getString("refCode");
					if ("1".equals(refCode)) {
						order.setOrderStatus(OrderStatus.Success.getValue());
						resp.setOriginalRespCode(Resp.Success.getCode());
						resp.setOriginalRespMsg(Resp.Success.getMsg());
					} else if ("3".equals(refCode) || "4".equals(refCode) || "6".equals(refCode)
							|| "8".equals(refCode)) {
						order.setOrderStatus(OrderStatus.InProcess.getValue());
						resp.setOriginalRespCode(Resp.InProcess.getCode());
						resp.setOriginalRespMsg(Resp.InProcess.getMsg());
					} else {
						order.setOrderStatus(OrderStatus.Fail.getValue());
						resp.setOriginalRespCode(Resp.Fail.getCode());
						resp.setOriginalRespMsg(Resp.Fail.getMsg());
					}
					order.update();
				}
			}
		} catch (Exception e) {
			FSLog.api.error("布子支付代付查询异常:" + e);
			resp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
		}
		return resp;
	}

	@Override
	public UnionPayResp unionpay(UnionPayReq req, TradeOrder order) throws Exception {
		return null;
	}

	@Override
	public QuickPaySetResp quickPaySet(QuickPaySetReq req, TradeOrder order) throws Exception {
		return null;
	}

	@Override
	public QuickPayResp quickPay(QuickPayReq req, TradeOrder order) throws Exception {
		return null;
	}

	@Override
	public SendSMSResp sendSMS(SendSMSReq req) throws Exception {
		return null;
	}

	@Override
	public QueryCardInfoResp queryCardInfo(QueryCardInfoReq req) throws Exception {
		return null;
	}

	@Override
	public RefundResp refund(RefundReq req, TradeOrder refundOrder, TradeOrder orignOrder) throws Exception {
		return null;
	}

}
